﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RFID信息初始化工作台
{
    public partial class Form1 : Form
    {
        FK _fk = new FK();
        int _itype = 0;

        public bool _bTest = false;

        public Form1()
        {
            InitializeComponent();

            if(Program._Language == Program.Language.Eng)
            {
                tsb_ShowSelect.Text = "Load Data Xls";
                lbl_Status.Text = "Default state";
                cmb_KFZT.Items.Clear();
                cmb_KFZT.Items.Add("In");
                cmb_KFZT.Items.Add("Out");
            }

            cmb_KFZT.SelectedIndex = 0;
            treeView1.AfterSelect += TreeView1_AfterSelect;

            groupBox1.Visible = false;
            if (_bTest)
                this.Text = "当前为发卡设备测试状态： 请连接设备后点击发卡按钮（可重复进行测试），来确认是否发卡稳定!";
            else
            {
                this.Text = Commons._sContent;
                var list = SGArchiveSystem7xDB.Linq.T_ArchiveTreeDal.Get_ArchiveTree();
                if (Program._Language == Program.Language.Chs)
                    treeView1.Nodes.Add("key", "物品分类", 0, 0);
                else
                    treeView1.Nodes.Add("key", "classification", 0, 0);
                if (list != null && list.Count > 0)
                {
                    foreach (var n in list)
                    {
                        TreeNode tn = new TreeNode();
                        tn.Text = n.AR_NAME;
                        tn.Tag = n;
                        tn.SelectedImageIndex = tn.ImageIndex = 1;
                        treeView1.Nodes[0].Nodes.Add(tn);
                    }
                }
                treeView1.ExpandAll();
            }
        }

        private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            ///根据加载列数据
            var en = treeView1.SelectedNode.Tag as SGArchiveSystem7xDB.T_ArchiveTree;
            listView_File.Items.Clear();
            listView_File.Columns.Clear();
            if (en != null)
            {
                int count = 0;
                var list = SGArchiveSystem7xDB.Linq.T_ArchiveFieldsDal.Get_ArchiveFields(out count, 1, en.AR_ID);
                foreach(var n  in list)
                {
                    ColumnHeader header = new ColumnHeader();
                    header.Text = n.AF_NAME;
                    header.Width = 100;
                    header.Tag = n;
                    listView_File.Columns.Add(header);
                }
            }
        }

        private void tsb_LoadPath_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsb_LoadAll_Click(object sender, EventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(ThLoadAll);
            th.Start();
        }

        private void ThLoadAll()
        {
            CheckForIllegalCrossThreadCalls = false;
            this.Enabled = false;
            ///listView_File.Items.Clear();
            try
            {
                pb.Maximum = listView_File.Items.Count;
                pb.Minimum = 0;
                pb.Value = 0;
                SGArchiveSystem7xDB.SGArchiveSystem7xEntities conn = new SGArchiveSystem7xDB.SGArchiveSystem7xEntities();
                ///数据核对
                for(int i=0;i<listView_File.Items.Count;i++)
                {
                    try
                    {
                        string key = listView_File.Items[i].SubItems[0].Text;
                        var en = conn.T_ArchiveAj.Select(c => c).Where(c => c.DH == key).ToList();
                        if (en == null || en.Count() == 0)
                        {
                            listView_File.Items[i].BackColor = Color.White;
                            listView_File.Items[i].ImageIndex = 0;
                        }
                        else
                        {
                            listView_File.Items[i].BackColor = Color.GreenYellow;
                            listView_File.Items[i].Tag = en[0].ID;
                            listView_File.Items[i].ImageIndex = 1;
                        }
                    }
                    catch
                    {
                        listView_File.Items[i].BackColor = Color.Red;
                        listView_File.Items[i].ImageIndex = 2;
                    }
                    finally
                    {
                        pb.Value = i + 1;
                    }
                }

                //YDRFIDEntities conn = new YDRFIDEntities();
                //var query = conn.T_RFID.Select(c => c).Where(c => c.RFID_TAG == null || c.RFID_TAG == "").OrderBy(c => c.RFID_DH).ToList();
                //int index = 1;
                //try
                //{
                //    foreach (var n in query)
                //    {
                //        string tm = (n.RFID_TM == null ? "" : n.RFID_TM);
                //        string tag = (n.RFID_TAG == null ? "" : n.RFID_TAG);
                //        ListViewItem item = new ListViewItem(new string[] { index.ToString(), tag, n.RFID_ATYPE, n.RFID_DH, tm, "", "" });
                //        item.Tag = n;
                //        listView_File.Items.Add(item);
                //        index++;
                //    }
                //    MessageBox.Show("加载完成!");
                //}
                //catch (Exception ex) { MessageBox.Show("发生错误! 错误内容: " + ex.Message); }
                //this.Enabled = true;
            }
            catch {
                if (Program._Language == Program.Language.Chs)
                    MessageBox.Show("未连接数据库!");
                else
                    MessageBox.Show("Database Error");
            }

            this.Enabled = true;
        }

        private void ThLoadMy()
        {
            //CheckForIllegalCrossThreadCalls = false;
            //this.Enabled = false;
            //listView_File.Items.Clear();
            //YDRFIDEntities conn = new YDRFIDEntities();
            //var query = conn.T_RFID.Select(c => c).Where(c => c.RFID_USER == Commons._enUser.U_RNAME).OrderBy(c => c.RFID_DH).ToList();
            //int index = 1;

            //foreach (var n in query)
            //{
            //    string tm = (n.RFID_TM == null ? "" : n.RFID_TM);
            //    string tag = (n.RFID_TAG == null ? "" : n.RFID_TAG);
            //    ListViewItem item = new ListViewItem(new string[] { index.ToString(), tag, n.RFID_ATYPE, n.RFID_DH, tm, n.RFID_DATE.Value.ToString("yyyy-MM-dd HH:mm"), n.RFID_USER });
            //    item.Tag = n;
            //    listView_File.Items.Add(item);
            //    index++;
            //}
            //MessageBox.Show("加载完成!");
            //this.Enabled = true;
        }

        private void tsb_LoadMy_Click(object sender, EventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(ThLoadMy);
            th.Start();
        }

        private void tsb_ShowSelect_Click(object sender, EventArgs e)
        {
            if (listView_File.Columns.Count == 0)
            {
                if (Program._Language == Program.Language.Chs)
                    MessageBox.Show("请先点击货物类型，才能加载XLS表", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("Please click on the goods type before loading the XLS form", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                OpenFileDialog of = new OpenFileDialog();
                of.Filter = "*.xls|*.xls|*.xlsx|*.xlsx";
                if (of.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        listView_File.Items.Clear();
                        ////加载xls数据
                        Aspose.Cells.Workbook book = new Aspose.Cells.Workbook(of.FileName);
                        Aspose.Cells.Worksheet sheet = book.Worksheets[0];
                        Aspose.Cells.Cells cells = sheet.Cells;

                        int[] ints = new int[listView_File.Columns.Count];
                        for (int i = 0; i < ints.Length; i++)
                            ints[i] = -1;
                        for (int j = 0; j < listView_File.Columns.Count; j++)
                        {
                            string header = listView_File.Columns[j].Text;
                            for (int i = 0; i < 30; i++)
                            {
                                if (cells[0, i].Value != null)
                                {
                                    string s = cells[0, i].Value.ToString();
                                    if (header == s)
                                    {
                                        ints[j] = i;
                                        break;
                                    }
                                }
                            }
                        }

                        if (ints[0] == -1)
                        {
                            if (Program._Language == Program.Language.Chs)
                                MessageBox.Show("物品编号必须包含在XLS表中，但此XLS中未能找到，请检查XLS后再操作此功能!");
                            else
                                MessageBox.Show("The item number must be included in the XLS table, but this XLS cannot be found. Please check the XLS before operating this function");
                            return;
                        }
                        string[] strs = new string[ints.Length];
                        for (int i = 1; i < cells.Rows.Count; i++)
                        {
                            int bh = ints[0];
                            if (cells[i, bh].Value == null || cells[i, bh].Value.ToString() == "")
                                break;
                            else
                            {
                                for (int j = 0; j < ints.Length; j++)
                                {
                                    int index = ints[j];
                                    if (index > -1)
                                        strs[j] = (cells[i, index].Value == null ? "" : cells[i, index].Value.ToString());
                                    else
                                        strs[j] = "";
                                }

                                listView_File.Items.Add(new ListViewItem(strs, -1));
                            }
                        }
                    }
                    catch
                    {
                        if (Program._Language == Program.Language.Chs)
                            MessageBox.Show("XL格式错误");
                        else
                            MessageBox.Show("XLS format error");
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            cmbCom.SelectedIndex = 0;
            //if (!_fk.Connection(_itype))
            //{
            //    MessageBox.Show("未连接发卡设备，或者没有安装发卡设备的驱动!");
            //    lbl_Info.ForeColor = Color.Red;
            //    lbl_Info.Text = "发卡设备无法连接";
            //}
            //else
            //{
            //    lbl_Info.ForeColor = Color.Blue;
            //    lbl_Info.Text = "发卡设备已连接";
            //}
            if (!_bTest)
            {
                this.Text += "  " + Commons._enUser.U_RNAME;
                toolStripButton4.Visible = false;
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            //if (!_fk.Connection())
            //{
            //    MessageBox.Show("未连接发卡设备，或者没有安装发卡设备的驱动!");
            //    lbl_Info.ForeColor = Color.Red;
            //    lbl_Info.Text = "发卡设备无法连接";
            //}
            //else
            //{
            //    lbl_Info.ForeColor = Color.Blue;
            //    lbl_Info.Text = "发卡设备已连接";
            //}
        }

        private void listView_File_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                 if(listView_File.SelectedItems.Count != 1)
                {
                    if (Program._Language == Program.Language.Chs)
                        MessageBox.Show("请选择一行数据进行初始化!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                        MessageBox.Show("Please select a row of data to initialize","Tip", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (listView_File.SelectedItems[0].ImageIndex == -1 || listView_File.SelectedItems[0].ImageIndex == 2)
                {
                    if (Program._Language == Program.Language.Chs)
                        MessageBox.Show("此数据没有对比，请先对比再进行标签初始化!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        MessageBox.Show("There is no comparison of this data, please compare and then initialize the label", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (listView_File.SelectedItems[0].ImageIndex == 1)
                {
                    if (Program._Language == Program.Language.Chs)
                    {
                        if (MessageBox.Show("此标签已经初始化过，还需要再次初始化吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                            return;
                    }
                    else
                    {
                        if (MessageBox.Show("This tag has been initialized，Still need to initialize again?", "Tip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                            return;
                    }
                }

                var tn = treeView1.SelectedNode.Tag as SGArchiveSystem7xDB.T_ArchiveTree;
                if (tn == null)
                {
                    MessageBox.Show("未获取物品类型信息!");
                    return;
                }

                int arid = tn.AR_ID;

                string tag = "AAAA" + Commons._enUser.U_ID.ToString().PadLeft(2, '0') + DateTime.Now.ToString("yyyyMMddhhmmssffff");

             
                if (!_fk.writeEPC(tag))
                    MessageBox.Show("标签初始化失败!");
                else
                {
                    int kfzt = 0;
                    if (cmb_KFZT.SelectedIndex == 0)
                        kfzt =(int)SGArchiveSystem7xDB._ArchiveKFStatus._iStatus_在库;
                    else
                        kfzt = (int)SGArchiveSystem7xDB._ArchiveKFStatus._iStatus_借出;

                    if (listView_File.SelectedItems[0].ImageIndex == 0)
                    {
                        string sql = "insert into t_archiveaj (arid, gdbm,bgqx,mj,kfzt,ajzt,sjjlr,sjjllx,sjjlrq,i05,";
                        for (int i = 0; i < listView_File.Columns.Count; i++)
                        {
                            var en = listView_File.Columns[i].Tag as SGArchiveSystem7xDB.T_ArchiveFields;
                            sql += en.AF_FIELD + ",";
                        }

                        if(cmb_KFZT.SelectedIndex == 1)
                            sql += "dzwj,v04) values(" + arid + ",1, 1, 6," + kfzt.ToString() + ",1,1,1,'" + DateTime.Now.ToString() + "',1,";
                        else
                            sql += "dzwj,v04,d02) values(" + arid + ",1, 1, 6," + kfzt.ToString() + ",1,1,1,'" + DateTime.Now.ToString() + "',1,";
                        for (int i = 0; i < listView_File.Columns.Count; i++)
                        {
                            sql += "'" + listView_File.SelectedItems[0].SubItems[i].Text + "',";
                        }
                        if (cmb_KFZT.SelectedIndex == 1)
                            sql += "'" + tag + "','" + tn.AR_NAME + "')";
                        else
                            sql += "'" + tag + "','" + tn.AR_NAME + "','" + DateTime.Now.ToString() + "')";

                        SGArchiveSystem7xDB.SGArchiveSystem7xEntities conn = new SGArchiveSystem7xDB.SGArchiveSystem7xEntities();
                        var dh = listView_File.SelectedItems[0].SubItems[0].Text;
                        if (conn.T_ArchiveAj.Select(c=>c).Where(c=>c.DH == dh).Count() > 0)
                        {
                            MessageBox.Show("唯一编号重复！无法添加");
                            return;
                        }

                        int value = SGArchiveSystem7xDB.Linq.T_ArchiveDal.Op_Archive(sql, "著录", Commons._enUser, listView_File.SelectedItems[0].SubItems[0].Text, 0, arid);
                        if (value > 0)
                        {
                            listView_File.SelectedItems[0].BackColor = Color.YellowGreen;
                            listView_File.SelectedItems[0].ImageIndex = 1;
                            listView_File.SelectedItems[0].Tag = value.ToString();
                            int index = listView_File.SelectedItems[0].Index;
                            if (index < listView_File.Items.Count - 1)
                            {
                                index++;
                                listView_File.Items[index].Focused = listView_File.Items[index].Selected = true;
                            }
                        }
                        else
                        {
                            MessageBox.Show("存入数据库失败！请检查xls格式对于系统对应关系是否正确！");
                        }
                    }
                    else if(listView_File.SelectedItems[0].ImageIndex == 1)
                    {
                        int id = int.Parse(listView_File.SelectedItems[0].Tag.ToString());
                        string sql = "update t_archiveaj set dzwj='" + tag + "' where id=" + id.ToString();
                        int value = SGArchiveSystem7xDB.Linq.T_ArchiveDal.Op_Archive(sql, "修改", Commons._enUser, listView_File.SelectedItems[0].SubItems[0].Text, id, arid);
                        if (value > 0)
                        {
                            listView_File.SelectedItems[0].BackColor = Color.YellowGreen;
                            listView_File.SelectedItems[0].ImageIndex = 1;

                            int index = listView_File.SelectedItems[0].Index;
                            if (index < listView_File.Items.Count - 1)
                            {
                                index++;
                                listView_File.Items[index].Focused = listView_File.Items[index].Selected = true;
                            }
                        }
                    }
                    else
                    {
                        if (Program._Language == Program.Language.Chs)
                            MessageBox.Show("加载的xls表数据未能通过对比，不能进行标签初始化!", "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        else
                            MessageBox.Show("The loaded xls table data failed to pass the comparison，Cannot perform label initialization!","Tip",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //_fk.Close();
            //_fk.EndClose();
            //_fk = null;

            groupBox1.Left = this.Width / 2 - groupBox1.Width / 2;
            groupBox1.Top = this.Height / 2 - groupBox1.Height / 2;
            groupBox1.Visible = true;

            
            //Form2 f = new Form2(cmbCom.SelectedIndex, cmbBL.SelectedIndex, cmbCom.SelectedItem.ToString());
            //f.ShowDialog();
            //_fk = new FK();
            //_fk.Connection(cmbCom.SelectedIndex, cmbBL.SelectedIndex, cmbCom.SelectedItem.ToString());
            ///_fk.Connection();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _fk.Close();
            _fk.EndClose();
        }

        private void tsb_User_Click(object sender, EventArgs e)
        {
            if (Commons._enUser.U_NAME != "admin")
            {
                if (Program._Language == Program.Language.Chs)
                    MessageBox.Show("只有管理员才能修改用户!");
                else
                    MessageBox.Show("Only admin can modify users");
            }
            else
            {
                frmUser frmUser = new frmUser();
                frmUser.ShowDialog();
            }
        }

        private void tsb_Diya_Click(object sender, EventArgs e)
        {
            _itype = 1;
            lbl_Info.Text = "采用自动寻找模式";
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            _itype = 0;
            lbl_Info.Text = "采用低电压模式";
        }

        private void cmbCom_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbBL.Items.Clear();
            if (cmbCom.SelectedIndex == 0)
            {
                cmbBL.Items.Add("9600bps");
                cmbBL.Items.Add("19200bps");
                cmbBL.Items.Add("38400bps");
                cmbBL.Items.Add("57600bps");
                cmbBL.Items.Add("115200bps");
                cmbBL.SelectedIndex = 3;
            }
            else
            {
                cmbBL.Items.Add("Auto");
                cmbBL.SelectedIndex = 0;
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            _fk.Close();
            _fk.EndClose();
           
            if (!_fk.Connection(cmbCom.SelectedIndex, cmbBL.SelectedIndex, cmbCom.SelectedItem.ToString()))
                return;
            else
            {
                if (Program._Language == Program.Language.Chs)
                    MessageBox.Show("设定成功!");
                else
                    MessageBox.Show("Set OK");
            }
        }

        private void toolStripButton4_Click_1(object sender, EventArgs e)
        {
            //_fk.Close();
            ///if (!_fk.Connection(cmbCom.SelectedIndex, cmbBL.SelectedIndex, cmbCom.SelectedItem.ToString()))
            ///    return;
            ////else
            {
                int count = 0;
                string s =  _fk.ReadEPC(out  count);
                if (s != "")
                    MessageBox.Show("读取成功!,共读取到 " + count.ToString() + " 个标签");
                else
                    MessageBox.Show("失败!");
                ////_fk.Close();
            }
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            listView_File2.Items.Clear();
            lbl_ReadInfo.Text = "";
            groupBox1.Visible = false;
        }

        private void btn_Read_Click(object sender, EventArgs e)
        {
            listView_File2.Items.Clear();
            int cardNumb = 0;
            string s =  _fk.ReadEPC(out cardNumb);
            ///_fk.Close();
            if (s == "") {
                if (Program._Language == Program.Language.Chs)
                    MessageBox.Show("未读到标签信息!");
                else
                    MessageBox.Show("No Reader Tag");
            }
            else if (!s.StartsWith("AAAA"))
                MessageBox.Show("标签格式不符合规范!");
            else
            {
                if (cardNumb > 1)
                    lbl_ReadInfo.Text = "读到至少: " + cardNumb.ToString() + " 个标签，请将其他标签移到远处进行读取";
                else
                    lbl_ReadInfo.Text = "读到标签数量: " + cardNumb.ToString();

                try
                {
                    //YDRFIDEntities conn = new YDRFIDEntities();
                    //var n = conn.T_RFID.Select(c => c).Where(c => c.RFID_TAG == s).Single();
                    //string tm = (n.RFID_TM == null ? "" : n.RFID_TM);
                    //string tag = (n.RFID_TAG == null ? "" : n.RFID_TAG);
                    //ListViewItem item = new ListViewItem(new string[] { "1", tag, n.RFID_ATYPE, n.RFID_DH, tm, n.RFID_DATE.Value.ToString("yyyy-MM-dd HH:mm"), n.RFID_USER });
                    //item.Tag = n;
                    //listView_File2.Items.Add(item);
                }
                catch
                {
                    //if (Program._Language == Program.Language.Chs)
                        MessageBox.Show("未找到匹配的档案信息!");
                    //else

                }
            }
        }

        private void btn_Writer_Click(object sender, EventArgs e)
        {
            if (listView_File2.Items.Count != 1)
            {
                MessageBox.Show("请先读取标签信息!");
                return;
            }

            if (listView_File2.Items[0].SubItems[1].Text != "")
            {
                if (MessageBox.Show("此标签已经初始化过，还需要再次初始化吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;
            }

            string tag = "AAAA" + Commons._enUser.U_ID.ToString().PadLeft(2, '0') + DateTime.Now.ToString("yyyyMMddhhmmssffff");
            if (!_fk.writeEPC(tag))
                MessageBox.Show("标签初始化失败!");
            else
            {

                //var n = listView_File2.Items[0].Tag as T_RFID;

                //YDRFIDEntities conn = new YDRFIDEntities();
                //var query = conn.T_RFID.Select(c => c).Where(c => c.RFID_ID == n.RFID_ID);
                //foreach (var nn in query)
                //{
                //    nn.RFID_DATE = DateTime.Now;
                //    nn.RFID_TAG = tag;
                //}
                //conn.SaveChanges();
                //MessageBox.Show("重写成功!");
                //listView_File2.Items.Clear();
            }
        }

        private void btn_Del_Click(object sender, EventArgs e)
        {
            if (listView_File2.Items.Count != 1)
            {
                MessageBox.Show("请先读取标签信息!");
                return;
            }

            if (listView_File2.Items[0].SubItems[1].Text != "")
            {
                if (MessageBox.Show("此标签已经初始化过，确定要抹除信息吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;
            }

            //var n = listView_File2.Items[0].Tag as T_RFID;

            //YDRFIDEntities conn = new YDRFIDEntities();
            //var query = conn.T_RFID.Select(c => c).Where(c => c.RFID_ID == n.RFID_ID);
            //foreach (var nn in query)
            //{
            //    nn.RFID_USER = null;
            //    nn.RFID_DATE = null;
            //    nn.RFID_TAG = null;
            //}
            //conn.SaveChanges();
            //MessageBox.Show("抹除成功!");
            //listView_File2.Items.Clear();
        }
    
    }
}
